package com.itheima.config;

import com.itheima.security.HealthUserDetilServiceImpl;
import com.itheima.security.JWTAuthenticationFilter;
import com.itheima.security.JWTAuthorizationFilter;
import com.itheima.security.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启权限注解
//开启配置类注解,可以扫描带@ConfigurationProperties(prefix = "health.jwt")的注解,并实例化放入springboot中
@EnableConfigurationProperties(JwtProperties.class)
public class HealthWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private HealthUserDetilServiceImpl healthUserDetilService;

    @Autowired
    private  JwtProperties properties;  //  注入 jwt需要公钥和私钥 配置类

    //创建一个密码加密的方法
    @Bean
    public PasswordEncoder createPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //重写用户认证信息
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库版
        auth.userDetailsService(healthUserDetilService).passwordEncoder(createPasswordEncoder());

     }

    //配置自己的登录页面
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().
                disable(). // crsf   禁用
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))  // 启用 过滤器
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session
    }
}

